package net.butfly.bus.server.router;

import java.util.HashMap;
import java.util.Map;

import net.butfly.bus.config.bean.RouterBean;
import net.butfly.bus.server.ServerConfig;
import net.butfly.bus.server.router.impl.RandomRoutingPolicy;


/**
 * 路由策略工厂
 */
public class RoutingPolicyFactory {
	private static RoutingPolicyFactory ins = new RoutingPolicyFactory();

	public static RoutingPolicyFactory getInstance() {
		return ins;
	}

	/**
	 * 缓存的路由策略
	 */
	private Map<String, RoutingPolicy> insMap = new HashMap<String, RoutingPolicy>();

	/**
	 * 获取路由策略
	 * 
	 * @return
	 */
	public RoutingPolicy getPolicy() {
		RouterBean routerBean = ServerConfig.getRouterBean();
		RoutingPolicy directory = insMap.get(routerBean.getPolicy());
		if (directory == null) {
			synchronized (this) {
				if (RouterType.isPolicyOfRandom(routerBean.getPolicy())) {
					directory = new RandomRoutingPolicy();
				}
				if (directory != null) {
					insMap.put(routerBean.getPolicy(), directory);
				}
			}
		}
		return directory;
	}
}
